<template>
  <div class="orders-container">
    <div class="list-filter">
      <el-radio-group v-model="activeList" @change="fetchOrders">
        <el-radio-button label="all">全部订单</el-radio-button>
        <el-radio-button label="cancelable">可取消订单</el-radio-button>
        <el-radio-button label="refundable">可退款订单</el-radio-button>
        <el-radio-button label="used">已完成订单</el-radio-button>
      </el-radio-group>
    </div>
    <el-table 
      :data="orderList" 
      border 
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="orderId" label="订单号" width="200" />
      <el-table-column prop="roomName" label="会议室名称" width="120" />
      <el-table-column prop="startTime" label="开始时间" width="180">
        <template #default="{row}">
          {{ formatDate(row.startTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="endTime" label="结束时间" width="180">
        <template #default="{row}">
          {{ formatDate(row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="participantsNum" label="参会人数" width="100" />
      <el-table-column prop="createdAt" label="创建时间" width="180">
        <template #default="{row}">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
      <!-- 新增支付截止时间列 -->
      <el-table-column label="支付截止时间" width="180">
        <template #default="{row}">
          <el-tag v-if="row.status === 0" :type="statusTagType(0)">
            {{ formatDate(row.lockedUntil) }}
          </el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{row}">
          <el-tag :type="statusTagType(row.status)">
            {{ formatStatus(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="totalPrice" label="总金额" width="120">
        <template #default="{row}">
          ¥{{ row.totalPrice.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" v-if="activeList === 'refundable'">
        <template #default="{row}">
          <el-button 
            type="warning" 
            size="small" 
            @click="handleRefund(row.orderId)"
          >申请退款</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" v-if="activeList === 'cancelable'">
        <template #default="{row}">
          <el-button 
            type="danger" 
            size="small" 
            @click="handleCancel(row.orderId)"
          >取消订单</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" v-if="activeList === 'used'">
        <template #default="{row}">
          <el-button 
            type="primary" 
            size="small" 
            @click="showCommentDialog(row.orderId)"
          >评价</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 评价对话框 -->
    <el-dialog v-model="commentDialogVisible" title="评价订单" width="500px">
      <el-form :model="commentForm" :rules="commentRules" ref="commentForm">
        <el-form-item label="星级评分" prop="likesCount">
          <el-rate
            v-model="commentForm.likesCount"
            :max="5"
            show-score
            text-color="#ff9900"
            score-template="{value} 星"
          />
        </el-form-item>
        <el-form-item label="体验感受" prop="content">
          <el-input
            v-model="commentForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入您的体验感受（不少于5个字）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="commentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitComment">提交评价</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import dayjs from 'dayjs';
import qs from 'querystring';
export default {
  data() {
    return {
      orderList: [],
      loading: false,
      activeList: 'all', // 新增列表类型状态
      commentDialogVisible: false,
      commentForm: {
        orderId: '',
        likesCount: 0,
        content: ''
      },
      commentRules: {
        content: [
          { required: true, message: '请输入评价内容', trigger: 'blur' },
          { min: 5, message: '评价内容不能少于5个字', trigger: 'blur' }
        ]
      }
    };
  },
  mounted() {
    this.fetchOrders();
  },
  methods: {
    async fetchOrders() {
      this.loading = true;
      try {
        let apiPath;
        switch(this.activeList) {
          case 'cancelable':
            apiPath = 'api/customer/manegeOrders/listcancel';
            break;
          case 'refundable':
            apiPath = 'api/customer/manegeOrders/list';
            break;
          case 'used':
            apiPath = 'api/customer/manegeOrders/listused'; // 新接口路径
            break;
          default:
            apiPath = 'api/customer/manegeOrders/listall';
        }
        
        const response = await axios.get(apiPath);
        this.orderList = response.data.data;
      } catch (error) {
        console.error('获取订单失败:', error);
        this.$message.error('获取订单数据失败');
      } finally {
        this.loading = false;
      }
    },
    formatDate(timestamp) {
      return dayjs(timestamp).format('YYYY-MM-DD HH:mm');
    },
    formatStatus(status) {
      const statusMap = ['待支付', '已支付', '已取消', '已完成'];
      return statusMap[status] || '未知状态';
    },
    statusTagType(status) {
      const typeMap = ['warning', 'success', 'info', 'success'];
      return typeMap[status] || '';
    },
    async handleCancel(orderId) {
      try {
        const response = await axios.post('api/customer/manegeOrders/dircancel', null, {
          params: { orderId }
        });
        
        if(response.data.code === 200) {
          this.$message.success('取消成功');
          this.fetchOrders(); // 刷新列表
        } else {
          this.$message.error(response.data.info);
        }
      } catch (error) {
        console.error('取消失败:', error);
        this.$message.error('取消操作失败');
      }
    },
    async handleRefund(orderId) {
      try {
        const response = await axios.post('api/customer/manegeOrders/cancel', null, {
          params: { orderId }
        });
        
        if(response.data.code === 200) {
          this.$message.success('退款申请已提交');
          this.fetchOrders();
        } else {
          this.$message.error(response.data.info);
        }
      } catch (error) {
        console.error('退款申请失败:', error);
        this.$message.error('退款操作失败');
      }
    },
    showCommentDialog(orderId) {
      this.commentForm.orderId = orderId;
      this.commentDialogVisible = true;
    },
    async submitComment() {
      try {
        const response = await axios.post('api/comment/commentadd', qs.stringify(this.commentForm),{
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        });
        if(response.data.code === 200) {
          this.$message.success('评价提交成功');
          this.commentDialogVisible = false;
        } else {
          this.$message.error(response.data.info);
        }
      } catch (error) {
        console.error('评价提交失败:', error);
        this.$message.error('评价提交失败');
      }
    }
  }
};
</script>

<style scoped>
.list-filter {
  margin-bottom: 20px;
}
.orders-container {
  padding: 20px;
  min-width: 1200px;
}

.el-table {
  margin-top: 20px;
}

.el-tag {
  margin: 2px;
}

/* 评价对话框样式 */
.el-rate {
  margin-top: 8px;
}
.el-textarea {
  margin-top: 8px;
}
</style>